import axios, {AxiosError} from 'axios'
import store from '../store'
import {message, notification} from 'antd'

interface ResponseData {
    success: boolean
    statusCode: number
    msg?: string
    data?: any

    [key: string]: any
}

//取消请求，请求失败都会有error
//
function handleError(err: AxiosError) {
    if (!axios.isCancel(err)) {
        const response = err.response;
        // debugger;
        notification.error(
            {
                message: `Error Code: ${response?.status ? response?.status : -1}`,
                description: response?.statusText ? response.statusText : '服务器出小差了'
            }
        )
    }

}

////

const request = axios.create({
    timeout: 15000,
    baseURL: '/api',
    withCredentials: true,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Access-Control-Allow-Origin': '*',
        "accept": "application/json"
    }

});

//取消请求
const CancelToken = axios.CancelToken;

//添加请求拦截器
request.interceptors.request.use((config) => {
    //取消重复请求(并非所有球球都是取消重复请求)
    const method = config.method;
    // debugger;
    const url = config.url;
    //TODO 这个地方获取token
    const userState = '';//获取token
    // 不添加会有错误提示，该错误是在调用拦截器函数时，Axios为其API定义其TypeScript类型的方式config
    //是undefined，
    if (config.headers === undefined) {
        config.headers = {};
    }
//TODO 这个地方获取token
    config.headers.token = '';


    return config;
}, (error) => {
    // debugger;
    handleError(error);
    return Promise.reject(error);

});
//添加响应拦截器
request.interceptors.response.use((response) => {
    const headers = response.config.headers;
    const data: ResponseData = response.data;
    // debugger;
    //请求失败
    if (data.success === false) {
        // debugger;
        notification.error({
            message: `错误码：${data.statusCode ? data.statusCode : -1}`,
            description: data.message ? data.message : '服务器出小差了',
        })
    }
    // debugger;
    if (data.statusCode === 401) {
        message.info('没有访问权限，请登录');
        //退出登录
        // setTimeout(logout,2000);
    }
    // 因为用了TS，类型限制了只能返回res，不能返回data
    return response;

    // return data;

}, error => {
    handleError(error);
    // debugger;
    return Promise.reject(error);
});
export default request;
